package com.framework.core.interceptor;

import com.framework.core.constant.Globals;
import com.framework.core.domain.SessionVo;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CommonInterceptor extends HandlerInterceptorAdapter {

    static Logger logger = Logger.getLogger(CommonInterceptor.class);

    private List<String> allowUrls;

    public void setAllowUrls(List<String> allowUrls) {
        this.allowUrls = allowUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        request.setAttribute("startTime", new Timestamp(System.currentTimeMillis()));//进入后台时间
        String requestUri = request.getRequestURI();
        if(requestUri.equals("/")) {
            return true;
        }
        for (String url : allowUrls) {
            if (requestUri.contains(url)) {
                return true;
            }
        }

        HttpSession session = request.getSession();
        SessionVo user = (SessionVo) session.getAttribute(Globals.USER_SESSION);
        if (null == user) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html; charset=utf-8");
            PrintWriter out = response.getWriter();
            StringBuilder builder = new StringBuilder();
            builder.append("<script type=\"text/javascript\" charset=\"utf-8\">");
            //builder.append("alert(\"页面过期，请重新登录！\");");
            builder.append("window.top.location.href=\"");
            builder.append("/\";</script>");
            out.print(builder.toString());
            out.close();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


        String requestUri = request.getRequestURI();
        HttpSession session = request.getSession();
        SessionVo sessionVo = (SessionVo) session.getAttribute("sessionVo");
        Timestamp startTime = (Timestamp) request.getAttribute("startTime");
        if(null == startTime){
            startTime = new Timestamp(System.currentTimeMillis());
        }
        Timestamp endTime = new Timestamp(System.currentTimeMillis());
        long time = endTime.getTime()-startTime.getTime();

        int refreshTime = 1000;
        if(time > refreshTime ){
            String userName = "";
            String iface = "";
            if(null != sessionVo){
                userName = sessionVo.getUserName();
            }else{
                if(null != request.getAttribute("username")){
                    userName= request.getAttribute("username").toString();
                }
                if(null != request.getAttribute("interface")){
                    iface = "接口:" +request.getAttribute("interface");
                }
            }
            logger.info(userName +"  " + iface +"  " +request.getRequestURI()+ "  "+startTime +"--->"+endTime  +"   时间差："+time);
        }
    }
}
